package com.hyzx.qbasic.admin.domain.service.impl;

import com.hyzx.qbasic.admin.model.constant.CommonConst;
import com.hyzx.qbasic.admin.model.po.CommonAttachmentPO;
import com.hyzx.qbasic.admin.model.po.CommonImagePO;
import com.hyzx.qbasic.admin.model.vo.res.BaseOperationRes;
import com.hyzx.qbasic.admin.model.vo.res.UploadFileResModel;
import com.hyzx.qbasic.admin.common.util.OperationResUtils;
import com.hyzx.qbasic.common.util.UuidUtils;
import com.hyzx.qbasic.admin.common.config.LocalStorageConfig;
import com.hyzx.qbasic.admin.domain.repository.ICommonFileRepository;
import com.hyzx.qbasic.admin.domain.service.ICommonFileService;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by 黄江华 on 2018/7/31
 */

@Service
@ConditionalOnProperty(value = "file.storage.service", havingValue = "local", matchIfMissing = true)
public class LocalFileServiceImpl implements ICommonFileService {
    private static final Logger logger = LoggerFactory.getLogger(LocalFileServiceImpl.class);

    @Autowired
    private ICommonFileRepository commonFileRepository;

    @Autowired
    private LocalStorageConfig localStorageConfig;

    @Override
    public UploadFileResModel uploadFile(String businessId, int priority, MultipartFile multipartFile) {
        UploadFileResModel res = new UploadFileResModel();
        res.setUploaded(0);

        if (multipartFile == null || multipartFile.isEmpty())
            return res;

        //生成新的文件名及存储位置
        String fileName = multipartFile.getOriginalFilename();
        String newFileName = UuidUtils.getObjectId().concat(fileName.substring(fileName.lastIndexOf(".")));

        String filePath = localStorageConfig.getAttachmentRootDir().concat("/")
                .concat(DateTime.now().toString(CommonConst.DATE_FORMAT_YYYY_MM))
                .concat("/")
                .concat(newFileName);

        String fullPath = localStorageConfig.getFileUploadLocation().concat(filePath);

        BaseOperationRes result = this.uploadFile(fullPath, multipartFile);
        if (result.isSuccess()) {
            String fileUrl = localStorageConfig.getFileUploadUrl().concat(filePath);

            CommonAttachmentPO attachmentPO = new CommonAttachmentPO();
            attachmentPO.setBusinessId(businessId);
            attachmentPO.setFileName(fileName);
            attachmentPO.setFilePath(fileUrl);
            attachmentPO.setFileSize(multipartFile.getSize());
            attachmentPO.setPriority(priority);
            attachmentPO.setCreateTime(new Date());
            commonFileRepository.saveFile(attachmentPO);

            res.setUploaded(1);
            res.setFileId(attachmentPO.getFileId());
            res.setFileName(fileName);
            res.setUrl(fileUrl);
            return res;
        }

        return res;
    }

    @Override
    public UploadFileResModel uploadImage(String businessId, int priority, MultipartFile multipartFile) {
        UploadFileResModel res = new UploadFileResModel();
        res.setUploaded(0);

        if (multipartFile == null || multipartFile.isEmpty())
            return res;

        //生成新的文件名及存储位置
        String fileName = multipartFile.getOriginalFilename();
        String newFileName = UuidUtils.getObjectId().concat(fileName.substring(fileName.lastIndexOf(".")));

        String imgPath = localStorageConfig.getImageRootDir().concat("/")
                .concat(DateTime.now().toString(CommonConst.DATE_FORMAT_YYYY_MM))
                .concat("/")
                .concat(newFileName);

        String fullPath = localStorageConfig.getFileUploadLocation().concat(imgPath);

        BaseOperationRes result = this.uploadFile(fullPath, multipartFile);
        if (result.isSuccess()) {
            String imgUrl = localStorageConfig.getFileUploadUrl().concat(imgPath);

            CommonImagePO imagePO = new CommonImagePO();
            imagePO.setBusinessId(businessId);
            imagePO.setImgName(fileName);
            imagePO.setImgPath(imgUrl);
            imagePO.setPriority(priority);
            imagePO.setCreateTime(new Date());
            commonFileRepository.saveImage(imagePO);

            res.setUploaded(1);
            res.setFileId(imagePO.getImgId());
            res.setFileName(fileName);
            res.setUrl(imgUrl);
            return res;
        }

        return res;
    }

    @Override
    public BaseOperationRes deleteAttachment(Integer fileId, String businessId) {
        BaseOperationRes res = OperationResUtils.fail("删除附件失败");

        CommonAttachmentPO attachment = commonFileRepository.getAttachmentInfo(fileId);
        if (attachment != null && attachment.getBusinessId().equals(businessId)) {
            boolean success = commonFileRepository.deleteAttachment(fileId);
            if (success) {
                String filePath = attachment.getFilePath().replace(localStorageConfig.getFileUploadUrl(),
                        localStorageConfig.getFileUploadLocation());

                File file = new File(filePath);
                if (file.exists()) {
                    if (file.delete())
                        res = OperationResUtils.success();
                }
            }
        }

        return res;
    }

    @Override
    public BaseOperationRes deleteImage(Integer imageId, String businessId) {
        BaseOperationRes res = OperationResUtils.fail("删除图片失败");

        CommonImagePO imageInfo = commonFileRepository.getImageInfo(imageId);
        if (imageInfo != null && imageInfo.getBusinessId().equals(businessId)) {
            boolean success = commonFileRepository.deleteImage(imageId);
            if (success) {
                String filePath = imageInfo.getImgPath().replace(localStorageConfig.getFileUploadUrl(),
                        localStorageConfig.getFileUploadLocation());

                File file = new File(filePath);
                if (file.exists()) {
                    if (file.delete())
                        res = OperationResUtils.success();
                }
            }
        }

        return res;
    }

    @Override
    public List<CommonAttachmentPO> getAttachmentList(String businessId) {
        return commonFileRepository.getAttachmentList(businessId);
    }

    @Override
    public List<CommonImagePO> getImageList(String businessId) {
        return commonFileRepository.getImageList(businessId);
    }

    private BaseOperationRes uploadFile(String filePath, MultipartFile multipartFile) {
        try {
            File target = new File(filePath);
            if (!target.getParentFile().exists()) { //判断文件父目录是否存在
                target.getParentFile().mkdirs();
            }

            byte[] data = multipartFile.getBytes();

            FileOutputStream fileOutputStream = new FileOutputStream(target.getAbsolutePath());
            fileOutputStream.write(data);
            fileOutputStream.flush();
            fileOutputStream.close();

            return OperationResUtils.success();
        } catch (IOException ex) {
            logger.error("上传文件异常", ex);
        }

        return OperationResUtils.fail("上传文件失败");
    }
}
